<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '修改入库单' : '新建入库单'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: true,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的入库单${entity.caseid}`, variables: {} }),
      submit: submitAudit,
      finish: () => submitAudit(),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <FormHolder ref="form" label-width="100px" :model="entity" :disabled="entity.status === '3'">
      <FormItemGroup block-title="基本信息">
        <FormInput v-model="entity.caseid" prop="caseid" label="入库单号" disabled />
        <FormInput v-model="entity.createBy" prop="createBy" label="入库人" disabled />
        <FormInput v-model="entity.createTime" prop="createTime" label="入库时间" disabled />
        <FormInput v-model="entity.amount" :span="12" prop="amount" label="入库总金额" disabled />
        <FormInput v-model="entity.deptFullname" :span="12" prop="deptFullname" label="入库单位" disabled />
        <FormInput v-model="entity.parentCaseid" :span="12" prop="parentCaseid" label="验收单号" disabled />
        <FormSelect
          v-model="entity.contractId"
          :options="dictData.contractTreeList"
          prop="contractId"
          legacy
          value-prop="id"
          filterable
          label-prop="name"
          label="合同或发票"
          required />
        <FormSelect
          v-model="entity.supplierId"
          :options="dictData.supplierTreeList"
          prop="supplierId"
          legacy
          value-prop="id"
          filterable
          label-prop="name"
          label="供应商"
          required />

        <FormItem label="房间名称" :span="12" prop="houseId" label-width="100px">
          <VueTreeSelect
            v-model="entity.houseId"
            :options="dictData.houseTreeList"
            :disable-branch-nodes="true"
            :class="['form-tree-select', { 'is-readonly': false }]"
            :disabled="entity.status === '3'"
            :show-count="true"
            :normalizer="normalizer"
            no-options-text="无房屋选项"
            placeholder="请选择房屋"
            @select="onHouseNodeClick" />
        </FormItem>
        <FormSelect
          v-model="entity.locationId"
          label="存放地点"
          filterable
          :options="positionList"
          value="value"
          prop="locationId" />

        <FormSelect
          v-model="entity.method"
          label="采购方式"
          :options="dictData.purchaseWayList"
          prop="purchaseWayList" />
        <FormSelect
          v-model="entity.currencyType"
          dict-type="currency_type"
          classic
          label="货币类型"
          prop="currencyType" />
        <FormTextarea v-model="entity.explains" label="入库说明" prop="explains" />
        <ElCol :span="24">
          <FlexRow vertical-center style="padding: 10px">
            <FlexItem><span style="color: #f56c6c">*</span>领用明细-物品列表</FlexItem>
            <ElButton size="mini" type="primary" class="el-icon-circle-plus" @click="tableVisible = true">
              从验收单选择</ElButton
            >
            <ElButton size="mini" type="primary" class="el-icon-circle-plus" @click="isPickerShow = true">
              添加</ElButton
            >
            <ElButton size="mini" type="primary" class="el-icon-delete" @click="deleteSelectCard"> 删除所选</ElButton>
          </FlexRow>
          <FormTable
            ref="formTable"
            v-model="entity.warehousList"
            prop="warehousList"
            required
            selection-width="60"
            placeholder="请选择物品"
            editable
            :show-summary="true"
            hide-label
            :handle-column="false"
            :columns="columns" />
        </ElCol>
      </FormItemGroup>
      <FormItemGroup :gutter="0" block-title="附件信息">
        <UploadPage
          v-if="entity.unid"
          ref="UploadPage"
          style="padding: 0"
          :unique-code="entity.unid"
          model="receive"
          classify="purchaseOrder" />
      </FormItemGroup>
    </FormHolder>
    <!-- 流程发送选择框 -->
    <FlowableHandleUserTable :visible.sync="visibleUser" :selection="true" :multiple="true" />
    <AssetCardTable
      :visible.sync="isPickerShow"
      :asset-card-id="entity.id"
      :in-type="entity.type"
      :multiple="true"
      @confirm="onConfirm" />
    <SelectAcTable :visible.sync="tableVisible" @confirm="onAcList" />
  </FormView>
</template>

<script>
  import { addObj, edit, putObj, createWarehous } from '@/api/asset/warehous'

  import FlowableHandleUserTable from '@/module/process/components/FlowableHandleUserTable.vue'
  import flowForm from '@/vue/mixin/flow-form'
  import { delWarehousListObj } from '@/api/asset/warehouslist'
  import { getPositionListByHouseId } from '@/api/space/fyroomposition'

  export default {
    name: 'WarehousForm',
    docType: 'WF_WAREHOUS',
    relativeViewId: 'WarehousView',
    components: {
      FlowableHandleUserTable
    },
    mixins: [flowForm],
    data() {
      return {
        columns: [
          { label: '资产分类', prop: 'ctiName' },
          { label: '资产名称', prop: 'name' },
          { label: '规格型号', prop: 'model' },
          { label: '条型码', prop: 'barcode' },
          { label: '计量单位', prop: 'unit' },
          { label: '入库数量', prop: 'quantity', required: true, type: 'number' },
          { label: '单价', prop: 'price' },
          { label: '总价', prop: 'amount' }
        ],
        selectedRows: [],
        isPickerShow: false,
        tableVisible: false,
        entity: {
          id: '',
          unid: '7d796bc4-e0a6-41bb-a325-471d60d2ae30',
          createBy: '李岳',
          createTime: '2023-04-27 10:46:32',
          deptId: '254',
          deptFullname: '广州海洋地质调查局',
          updateBy: null,
          updateTime: null,
          createId: '1187',
          type: 'ALL',
          caseid: null,
          parentId: null,
          classify: '0',
          parentCaseid: null,
          batchnumber: null,
          contractId: null,
          contractNumber: null,
          contractName: null,
          status: '0',
          supplierId: null,
          supplierName: null,
          inTime: null,
          houseName: null,
          houseId: null,
          locationName: null,
          locationId: null,
          fullLocation: null,
          method: null,
          amount: null,
          currencyType: '人民币',
          detailed: '',
          explains: null,
          warehousList: [],
          dictOption: {
            statusList: [],
            purchaseWayList: [],
            currencyTypeList: [],
            contractTreeList: [],
            supplierTreeList: [],
            deptTreeList: [],
            houseTreeList: [],
            positionTreeList: []
          }
        },
        visibleUser: false,
        positionList: []
      }
    },
    watch: {
      entity: {
        handler(newVal, oldVal) {
          if (newVal.houseId) {
            this.loadPositionList(newVal.houseId)
          }
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      create: createWarehous,
      load: edit,
      save: addObj,
      update: putObj,
      onConfirm(rows) {
        if (!this.entity.warehousList?.length) {
          rows.forEach(row => {
            this.$set(row, 'quantity', row.orderQuantity || undefined)
            this.entity.warehousList.push(row)
          })
        } else {
          rows.forEach(row => {
            this.$set(row, 'quantity', row.orderQuantity || undefined)
            if (!this.entity.warehousList.find(value => value.sauId === row.sauId)) {
              this.entity.warehousList.push(row)
            }
          })
        }
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.idCard,
          label: node.name,
          isDisabled: this.$isBlank(node.children) && !(node.affiliName === 'HOUSE'),
          children: node.children
        }
      },
      async onHouseNodeClick(node) {
        await this.loadPositionList(node.idCard)
      },
      async loadPositionList(houseId) {
        const res = await getPositionListByHouseId({ houseId })
        this.positionList = res.data.data
      },
      onAcList(rows) {
        rows.forEach(row => {
          this.$set(row, 'quantity', row.orderQuantity || undefined)
          this.entity.warehousList.push(row)
        })
        if (rows.length > 0) {
          const row = rows[0]
          this.entity.parentId = row.parentId
          this.entity.parentCaseid = row.parentCaseid
          this.entity.batchnumber = row.batchnumber
          this.entity.type = row.type
          this.entity.supplierId = row.supplierId
          this.entity.supplierName = row.supplierName
          this.entity.currencyType = row.currencyType
          this.entity.method = row.method
          this.entity.contractId = row.contractId
          this.entity.contractName = row.contractName
          this.entity.contractNumber = row.contractNumber
        }
      },
      deleteSelectCard() {
        this.selectedRows = this.$refs.formTable.selectedRows
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择所需要删除的物品列表')
          return
        }
        const deleteIds = this.selectedRows.filter(item => item.id > 0).map(item => item.id)
        this.$confirm(`是否确认删除"${this.selectedRows.length} "条明细数据？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (deleteIds.length > 0) {
              delWarehousListObj(deleteIds)
            }
            this.entity.warehousList = this.entity.warehousList.filter(value => !this.selectedRows.includes(value))
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      }
    }
  }
</script>
